package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.commons.ex.ServiceException;
import cn.tedu.csmall.commons.util.PageInfoToPageDataConverter;
import cn.tedu.csmall.commons.vo.PageData;
import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.product.mapper.BrandCategoryMapper;
import cn.tedu.csmall.product.mapper.BrandMapper;
import cn.tedu.csmall.product.mapper.SpuMapper;
import cn.tedu.csmall.product.pojo.entity.Brand;
import cn.tedu.csmall.product.pojo.entity.BrandCategory;
import cn.tedu.csmall.product.pojo.entity.Spu;
import cn.tedu.csmall.product.pojo.param.BrandAddNewParam;
import cn.tedu.csmall.product.pojo.param.BrandUpdateInfoParam;
import cn.tedu.csmall.product.pojo.vo.BrandListItemVO;
import cn.tedu.csmall.product.pojo.vo.BrandStandardVO;
import cn.tedu.csmall.product.service.IBrandService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Administrator
 * @description 针对表【pms_brand(品牌)】的数据库操作Service实现
 * @createDate 2023-06-13 10:34:11
 */
@Service
@Slf4j
public class BrandServiceImpl implements IBrandService {

    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private BrandCategoryMapper brandCategoryMapper;
    @Autowired
    private SpuMapper spuMapper;


    @Override
    public void addNew(BrandAddNewParam brandAddNewParam) {

        log.debug("开始处理[添加品牌]的业务，参数:{}", brandAddNewParam);

        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("name", brandAddNewParam.getName());
        int countByName = brandMapper.selectCount(queryWrapper);
        log.debug("根据品牌名称统计匹配的品牌数量，结果:{}", countByName);
        if (countByName > 0) {
            String message = "添加品牌失败，品牌名称已经被占用";
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Brand brand = new Brand();

        BeanUtils.copyProperties(brandAddNewParam, brand);
        brand.setSales(0);
        brand.setProductCount(0);
        brand.setCommentCount(0);
        ;
        brand.setProductCount(0);
        brand.setGmtCreate(LocalDateTime.now());
        brand.setGmtModified(LocalDateTime.now());
        log.debug("准备将新的品牌数据写入到数据库,数据：{}", brand);
        int rows = brandMapper.insert(brand);

        if (rows != 1) {
            String message = "添加属性模版失败！服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

        log.debug("将新的品牌数据写入到数据库，完成！");

    }

    @Override
    public void deleteById(Long id) {
        log.info("开始处理【删除品牌】的业务");
        log.debug("传入参数,id={}", id);

        //检查品牌ID检查品牌是否存在数据，如果不存在，则抛出异常
        QueryWrapper<Brand> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("id", id);
        int countById = brandMapper.selectCount(queryWrapper2);
        log.info("根据品牌id检索数据库结果,countById={}", countById);
        if(countById == 0){
            log.info("根据品牌id检索数据量为0，抛出异常...");
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "删除品牌失败，品牌数据不存在！");
        }

        //根据品牌ID检查属性表是否存在数据，如果存在，则抛出异常
        QueryWrapper<BrandCategory> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("brand_id", id);
        int countByBrandId3 = brandCategoryMapper.selectCount(queryWrapper3);
        log.info("根据品牌id检品牌品牌数据库结果,countByBrandId3={}", countByBrandId3);
        if(countByBrandId3 > 0){
            log.info("根据品牌id检索属性数据量>0，抛出异常...");
            throw new ServiceException(ServiceCode.ERR_CONFLICT, "删除品牌失败，品牌品牌表内有关联数据！");
        }

        //根据品牌ID检查Spu是否存在数据，如果存在，则抛出异常
        QueryWrapper<Spu> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("brand_id", id);
        int countByBrandId4 = spuMapper.selectCount(queryWrapper4);
        log.info("根据品牌id检索spu数据库结果,countByBrandId4={}", countByBrandId4);
        if(countByBrandId4 > 0){
            log.info("根据品牌id检索spu数据量>0，抛出异常...");
            throw new ServiceException(ServiceCode.ERR_CONFLICT, "删除品牌失败，spu内存在该品牌数据！");
        }

        int rows = brandMapper.deleteById(id);
        if(rows != 1){
            String message = "编辑品牌失败，服务器忙，请稍后再试！";
            log.info("数据返回行数不满足预估行数，预估={}, 实际={}, 抛出自定异常...", 1, rows);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        log.info("删除成功");
    }

    @Override
    public void updateInfoById(Long id, BrandUpdateInfoParam brandUpdateInfoParam) {
        log.info("开始处理【根据id更新品牌】的业务");
        log.debug("传入参数,id={},brandUpdateInfoParam={}", id, brandUpdateInfoParam);

        //检查品牌ID检查品牌是否存在数据，如果不存在，则抛出异常
        QueryWrapper<Brand> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("id", id);
        int countById = brandMapper.selectCount(queryWrapper2);
        log.info("根据品牌id检索数据库结果,countById={}", countById);
        if(countById == 0){
            log.info("根据品牌id检索数据量为0，抛出异常...");
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "编辑品牌失败，品牌数据不存在！");
        }

        //检查品牌名称是否被占用，如果被占用，则抛出异常
        QueryWrapper<Brand> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("name",brandUpdateInfoParam.getName())
                .ne("id", id);
        int countByName = brandMapper.selectCount(queryWrapper3);
        log.info("根据品牌名称检索数据库结果,countByName={}", countByName);
        if(countByName > 0){
            log.info("不满足品牌编辑规则，抛出自定异常...");
            throw new ServiceException(ServiceCode.ERR_CONFLICT, "编辑品牌失败，品牌名称已经被占用！");
        }

        Brand brand = new Brand();
        BeanUtils.copyProperties(brandUpdateInfoParam, brand);
        brand.setId(id);
        int rows = brandMapper.updateById(brand);
        if(rows != 1){
            String message = "编辑品牌失败，服务器忙，请稍后再试！";
            log.info("数据返回行数不满足预估行数，预估={}, 实际={}, 抛出自定异常...", 1, rows);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.info("修改品牌成功");
    }

    @Override
    public void setEnable(Long id) {
        updateEnableById(id, 1);
    }

    @Override
    public void setDisable(Long id) {
        updateEnableById(id, 0);
    }

    private void updateEnableById(Long id, Integer enable){
        String text = ENABLE_TEXT[enable];
        log.info("开始处理【" + text + "品牌】的业务");
        log.debug("参数,id={}, enable={} ", id, enable);

        //检查数据是否存在，如果不存在，则抛出异常
        BrandStandardVO brandStandardVO = brandMapper.getStandardById(id);
        log.info("根据品牌id检索数据库结果,brandStandardVO={}", brandStandardVO);
        if(brandStandardVO == null){
            String message = text + "品牌失败，品牌数据不存在！";
            log.info("根据品牌id检索数据量为0，抛出异常...");
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        if(brandStandardVO.getEnable().equals(enable)){
            String message = text + "品牌失败，此品牌已经处于" + text + "状态！";
            log.info("根据品牌启用状态与要修改状态一致，抛出异常...");
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Brand brand = new Brand();
        brand.setId(id).setEnable(enable);
        int rows = brandMapper.updateById(brand);
        if(rows != 1){
            String message = text+"品牌失败，服务器忙，请稍后再试！";
            log.info("数据返回行数不满足预估行数，预估={}, 实际={}, 抛出自定异常...", 1, rows);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.info("根据id更新品牌结果,rows={}", rows);
    }

    @Override
    public BrandStandardVO getStandardById(Long id) {
        log.info("开始:【根据ID查询品牌】");
        log.debug("传入参数,id={}", id);
        BrandStandardVO standardById = brandMapper.getStandardById(id);

        //根据品牌ID检查品牌是否存在数据，如果不存在，则抛出异常
        if(standardById==null){
            log.info("结果2:根据品牌id查询详情，结果为null，抛出异常...");
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "查询品牌详情失败，品牌数据不存在");
        }

        log.info("结果1:查询出数据,standardById");
        return standardById;
    }

    @Override
    public PageData<BrandListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum, pageSize);
    }

    @Override
    public PageData<BrandListItemVO> list(Integer pageNum, Integer pageSize) {
        log.info("开始:【查询-品牌-分页】");
        log.debug("传入参数, pageNum={}, pageSize={}", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<BrandListItemVO> list = brandMapper.list();
        PageInfo<BrandListItemVO> pageInfo = new PageInfo<>(list);
        PageData<BrandListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("结果1: 查询结果：pageData={}", pageData);
        return pageData;
    }
}




